import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      // config.headers['Authorization'] = `Bearer ${token}`;
      config.headers['usId'] = localStorage.getItem('usId')
      config.headers['token'] = token
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code === 200) {
      return res
    }

    if (res.code === 401) {
      Message.error('登录已过期，请重新登录')
      localStorage.removeItem('token')
      router.push('/login')
      return Promise.reject(new Error('未登录或登录过期'))
    }

    Message.error(res.message || '系统错误')
    return Promise.reject(new Error(res.message || '系统错误'))
  },
  error => {
    console.error('响应错误:', error)
    const message = error.response?.data?.message || '请求失败'
    Message.error(message)
    return Promise.reject(error)
  }
)

export default service 